#include "mjson.h"

//简单的json操作，不会校验buf长度是否足够
//接收处理需确保json格式字符串有字符串结束符

void mjson_start(mjson_handle_t *mjson,u8 *buf,u16 len)
{
	mjson->buf=buf;
	mjson->len=len;
	mjson->addr=0;
	mjson->buf[mjson->addr++]='{';
}
void mjson_add_int(mjson_handle_t *mjson,u8 *key,s32 value)
{
	mjson->buf[mjson->addr++]='\"';
	mjson->addr+=strlen(strcpy((char*)&mjson->buf[mjson->addr],(char*)key));
	mjson->buf[mjson->addr++]='\"';
	mjson->buf[mjson->addr++]=':';
	mjson->addr+=sprintf((char*)&mjson->buf[mjson->addr],"%d",value);
	mjson->buf[mjson->addr++]=',';
	mjson->buf[mjson->addr++]='\r';
	mjson->buf[mjson->addr++]='\n';
}
void mjson_add_double(mjson_handle_t *mjson,u8 *key,double value)
{
	mjson->buf[mjson->addr++]='\"';
	mjson->addr+=strlen(strcpy((char*)&mjson->buf[mjson->addr],(char*)key));
	mjson->buf[mjson->addr++]='\"';
	mjson->buf[mjson->addr++]=':';
	mjson->addr+=sprintf((char*)&mjson->buf[mjson->addr],"%g",value);
	mjson->buf[mjson->addr++]=',';
	mjson->buf[mjson->addr++]='\r';
	mjson->buf[mjson->addr++]='\n';
}
void mjson_add_str(mjson_handle_t *mjson,u8 *key,u8* value)
{
	mjson->buf[mjson->addr++]='\"';
	mjson->addr+=strlen(strcpy((char*)&mjson->buf[mjson->addr],(char*)key));
	mjson->buf[mjson->addr++]='\"';
	mjson->buf[mjson->addr++]=':';
	mjson->buf[mjson->addr++]='\"';
	mjson->addr+=strlen(strcpy((char*)&mjson->buf[mjson->addr],(char*)value));
	mjson->buf[mjson->addr++]='\"';
	mjson->buf[mjson->addr++]=',';
	mjson->buf[mjson->addr++]='\r';
	mjson->buf[mjson->addr++]='\n';
}
void mjson_end(mjson_handle_t *mjson)
{
	mjson->addr-=3;
	mjson->buf[mjson->addr++]='\r';
	mjson->buf[mjson->addr++]='\n';
	mjson->buf[mjson->addr++]='}';
	mjson->buf[mjson->addr++]='\0';
}


u8 *skip_space(u8 *buf)
{
	while(*buf<=32)	buf++;
	return buf;
}


//成功返回0
u8 mjson_get_int(u8 *buf,u8 *key,s32 *value)
{
	while(*buf){
		if(*buf!='\"'){
			buf++;
			continue;
		}
		if(0==strncmp((char*)buf+1,(char*)key,strlen((char*)key))){
			buf+=strlen((char*)key)+1;
			buf=skip_space(buf+1);
			buf=skip_space(buf+1);
			*value=strtol((char*)buf,NULL,10);
			return 0;
		}
		buf++;
	}
	return 1;
}
u8 mjson_get_double(u8 *buf,u8 *key,double *value)
{
	while(*buf){
		if(*buf!='\"'){
			buf++;
			continue;
		}
		if(0==strncmp((char*)buf+1,(char*)key,strlen((char*)key))){
			buf+=strlen((char*)key)+1;
			buf=skip_space(buf+1);
			buf=skip_space(buf+1);
			*value=strtod((char*)buf,NULL);
			return 0;
		}
		buf++;
	}
	return 1;
}
u8 mjson_get_str(u8 *buf,u8 *key,u8 **value)
{
	while(*buf){
		if(*buf!='\"'){
			buf++;
			continue;
		}
		if(0==strncmp((char*)buf+1,(char*)key,strlen((char*)key))){
			buf+=strlen((char*)key)+1;
			buf=skip_space(buf+1);
			buf=skip_space(buf+1);
			*value=buf+1;
			return 0;
		}
		buf++;
	}
	return 1;
}

